//https://lbs.amap.com/api/jsapi-v2/documentation#map

import AMapLoader from '@amap/amap-jsapi-loader'

let changeTimerOut: any = null
let renderTimeOut: any = null

export interface imapOption {
    viewMode: string,
    zoom: number,
    center: number[],
}

//初始化地图
export function initMap(id: string, option?: imapOption) {
    if (!id) return;
    return AMapLoader.load({
        key: "44d882073dcf9ca4cad0ca608db9af74", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Scale', 'AMap.MarkerClusterer'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        const map = new AMap.Map(id, {  //设置地图容器id
            viewMode: '2D', //是否为3D地图模式
            zoom: 9, //初始化地图级别
            layers: [new AMap.TileLayer.Satellite(), new AMap.TileLayer.RoadNet()],
            center: [102.647115, 24.670037], //初始化地图中心点位置
            ...option
        });
        return Promise.resolve({ map, AMap })
    }).catch(e => {
        console.log(e);
        return Promise.reject(e)
    })
}

//区域变更
export function onAreaChange(map: any, callback: Function) {
    let getBounds = (map: any) => {
        let area = map.getBounds()
        return {
            northEast: {
                lat: area.northEast.lat,
                lng: area.northEast.lng
            },
            southWest: {
                lat: area.southWest.lat,
                lng: area.southWest.lng
            }
        }
    }
    map.on('zoomend', (e: any) => {
        if (changeTimerOut) clearTimeout(changeTimerOut)
        changeTimerOut = setTimeout(() => {
            callback(getBounds(map))
        }, 500);
    })
    map.on('dragend', (e: any) => {
        if (changeTimerOut) clearTimeout(changeTimerOut)
        changeTimerOut = setTimeout(() => {
            callback(getBounds(map))
        }, 500);
    })
    callback(getBounds(map))
}

//添加图标
export function addMarkerCluster(map: any, AMap: any, points: { lnglat: number[], meta: object }[]) {
    if (!points) return
    const count = points.length
    const _renderClusterMarker = (context: any) => {
        if (renderTimeOut) clearTimeout(renderTimeOut)
        renderTimeOut = setTimeout(() => {
            let v = context.clusterData;
            console.log({ clusterData: v.map((f: any) => f.meta.id).join("-"), count: context.count })
            let div = document.createElement('div');
            let bgColor = 'rgb(255,0,0)';
            let fontColor = 'rgb(255,0,0)';
            let shadowColor = 'rgb(255,0,0)';
            div.style.backgroundColor = bgColor;
            let size = Math.round(20 + Math.pow(context.count / count, 1 / 5) * 10);
            div.style.width = div.style.height = size + 'px';
            div.style.borderRadius = size / 2 + 'px';
            div.style.boxShadow = '0 0 5px ' + shadowColor;
            div.innerHTML = context.count;
            div.style.lineHeight = size + 'px';
            div.style.color = "rgb(255,255,255)";
            div.style.fontSize = '14px';
            div.style.textAlign = 'center';
            context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
            context.marker.setContent(div)
        }, 200);
        context.marker.setContent(" ")
    }

    const _renderMarker = (context: any) => {
        let mark = context.marker
        var content = '<div class="device-mark"></div>';
        var offset = new AMap.Pixel(-9, -9);
        context.marker.setContent(content)
        context.marker.setOffset(offset)
        context.marker.setExtData(context.data[0].meta)
        context.marker.on("click", (e: any) => {
            console.log("marker click:", mark.getExtData())
        })
    }

    return new AMap.MarkerCluster(map, points, {
        gridSize: 60,
        maxZoom: 16,
        renderClusterMarker: _renderClusterMarker,
        renderMarker: _renderMarker,
    });
}

//注销地图
export function destroyedMap(map: any) {
    map.clearEvents()
}